package cn.sciento.farm.devicemanager.common.util;

import cn.sciento.farm.devicemanager.common.constant.ResultConstant;
import cn.sciento.farm.devicemanager.dao.model.ResponseMessage;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.List;
import java.util.Map;

public class ReturnUtil {

    public static ResponseMessage getReturnMap(ResultConstant code) {
        return getReturnMap(code, null);
    }


    public static ResponseMessage  getReturnMap(ResultConstant code, Object data) {
        return getReturnMap(code, data, null);
    }



    /**
     * 设置响应代码
     */
    public static ResponseMessage getReturnMap(ResultConstant code, Object data, Object otherMap) {
        ResponseMessage responseMessage = new ResponseMessage();
        if (data != null) {
            if (data instanceof IPage) {
                IPage<?> page = (IPage<?>) data;
                responseMessage.setData(page.getRecords());
                responseMessage.setSize( page.getSize());
                responseMessage.setPages( page.getPages());
                responseMessage.setCurrent(page.getCurrent());
                responseMessage.setTotal( page.getTotal());
            } else if (data instanceof List<?>) {
                responseMessage.setData( data);
                responseMessage.setSize((long) ((List<?>) data).size());
            } else if (data instanceof Number) {
                //对整数进行处理
                if (((Number) data).longValue() <= 0 || ((Number) data).longValue() > 10000) {
                    code = ResultConstant.match(((Number) data).intValue());
                } else {
                    if (((Number) data).longValue() == 0) {
                        code = ResultConstant.FAILED;
                    }
                }
                responseMessage.setData( otherMap);
            } else if (data instanceof Boolean) {
                boolean en = (Boolean) data;
                if (en) {
                    code = ResultConstant.FAILED;
                } else {
                    code = ResultConstant.SUCCESS;
                }
            } else {
                responseMessage.setData( data);
            }

        } else {
            responseMessage.setData( null);
        }
        if (otherMap != null) {
            responseMessage.setOther( otherMap);
        }
        responseMessage.setCode( code.getCode());
        responseMessage.setMsg( code.getMessage());
        responseMessage.setTimestamp(System.currentTimeMillis());
        return responseMessage;
    }
}
